package com.yjy.fuyao.stu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjy.fuyao.stu.client.VodVideoClient;
import com.yjy.fuyao.stu.entity.Video;
import com.yjy.fuyao.stu.entity.form.VideoInfo;
import com.yjy.fuyao.stu.mapper.VideoMapper;
import com.yjy.fuyao.stu.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author yjy
 * @since 2021-08-17
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Resource
    VodVideoClient vodVideoClient;

    @Override
    public boolean getCountByChapterId(String chapterId) {
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id", chapterId);
        Integer count = baseMapper.selectCount(queryWrapper);
        System.out.println("===================="+chapterId+"==================");
        System.out.println("===================="+count+"==================");
        return count != null && count > 0;
    }

    @Override
    public boolean saveOrUpdateVideoInfo(VideoInfo videoInfo) {
        Video video = new Video();
        BeanUtils.copyProperties(videoInfo,video);
        System.out.println("-------------"+"video:" + video+"-----------");
        boolean result = this.saveOrUpdate(video);
        return result;
    }

    @Override
    public VideoInfo getVideoInfoById(String id) {
        Video video = baseMapper.selectById(id);
        VideoInfo videoInfo = new VideoInfo();
        BeanUtils.copyProperties(video,videoInfo);
        return videoInfo;
    }

    @Override
    public boolean removeByCourseId(String courseId) {
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id",courseId);
        List<Video> videos = baseMapper.selectList(videoQueryWrapper);
        for (Video video:videos) {
            vodVideoClient.removeById(video.getVideoSourceId());
        }
        Integer result = baseMapper.delete(videoQueryWrapper);
        return null != result && result > 0;
    }

    @Override
    public boolean removeByVideoId(String id) {
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("id",id);
        Video video = baseMapper.selectOne(videoQueryWrapper);
        vodVideoClient.removeById(video.getVideoSourceId());
        Integer result = baseMapper.delete(videoQueryWrapper);
        return null != result && result > 0;
    }
}
